﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Acme.Sakila.TestSite.Objects;
using Acme.Sakila.EFDAL;
using nHydrate.EFCore.DataAccess;
using Acme.Sakila.EFDAL.Entity;

namespace Acme.Sakila.TestSite
{
	public partial class ActorList : BasePage
	{
		#region Page Events

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			grdItem.RowDataBound += new GridViewRowEventHandler(grdItem_RowDataBound);
			this.PagingControl1.ObjectSingular = "Actor";
			this.PagingControl1.ObjectPlural = "Actors";
			this.PagingControl1.RecordsPerPageChanged += new EventHandler(PagingControl1_RecordsPerPageChanged);
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			if (!this.IsPostBack)
			{
				this.Populate();
			}
		}

		#endregion

		#region Methods

		private void Populate()
		{
			using (var context = new SakilaEntities(Utils.ContextStartup))
			{
				var paging = new Paging(
					this.PagingControl1.PageIndex,
					this.PagingControl1.RecordsPerPage);

				List<actor> actorCollection = null;
				if (this.Request["filmid"] != null)
				{
					int filmId;
					int.TryParse(this.Request["filmId"], out filmId);
					var theFilm = context.film.FirstOrDefault(x => x.film_id == filmId);
					actorCollection = context.actor.GetPagedResults(x => x.filmList.Any(z => z.film_id == filmId), x => x.actor_id, paging).ToList();
					lblHeader.Text = "This is a list of all actors for film <a href='/FilmItem.aspx?id=" + theFilm.film_id + "'>" + theFilm.title + "</a>.";
				}
				else
				{
					actorCollection = context.actor.GetPagedResults(x => x.actor_id, paging).ToList();
				}

				this.PagingControl1.ItemCount = paging.RecordCount;
				grdItem.DataSource = actorCollection;
				grdItem.DataBind();
				SessionHelper.LastCategoryListSearch = this.Request.Url.AbsoluteUri;
			}
		}

		#endregion

		#region Event Handlers

		private void grdItem_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				var theActor = e.Row.DataItem as Acme.Sakila.EFDAL.Entity.actor;
				var linkEdit = (HyperLink)e.Row.FindControl("linkEdit");
				var linkFilms = (HyperLink)e.Row.FindControl("linkFilms");

				linkEdit.NavigateUrl = "/ActorItem.aspx?id=" + theActor.actor_id;
				linkFilms.NavigateUrl = "/FilmList.aspx?actorid=" + theActor.actor_id;
			}
		}

		private void PagingControl1_RecordsPerPageChanged(object sender, EventArgs e)
		{
			var query = new URL(this.Request.Url.AbsoluteUri);
			query.Parameters.SetValue("rpp", PagingControl1.RecordsPerPage.ToString());
			query.Parameters.SetValue("po", "1");
			this.Response.Redirect(query.ToString());
		}

		#endregion

	}
}